<template>
  <!-- 单面直出 这里的全部都是单面直出的情况 v-if="isDirectOutput" -->
  <section>

    <!--    这已经是一组数据了     -->
    <div :key="groupKey" style="margin-bottom: 15px"
         v-for="(groupKey,groupIdx) in Object.keys(shipmentData.groupByOrderCode)">
      <!--      <h3 style="margin: 15px;">订单号: {{groupKey}}</h3>-->
      <transition-group :gutter="3" name="list-complete" tag="el-row">
        <!--    一组的每一个格子    -->
        <el-col
          :key="bagCell['BagOrder']"
          :span="6"
          class="list-complete-item" style="margin: 3px 3px"
          v-for="(bagCell,bagIdx) in shipmentData.groupByOrderCode[groupKey]">
          <el-card>
            <!--     有合并包裹前和后两种不同的显示模板     -->
            <!--     condition one 没有合单的情况    -->
            <div class="bag-wrap">
              <VueBarCode
                :height="25"
                :value="bagCell.Code"
                displayValue="false"
                element-tag="img"
                width="1">
                条形码显示错误!
              </VueBarCode>

              <div>
                <div style="text-align: center">P/L:{{bagCell.Code}}</div>
                <div style="padding:5px;text-align: center">客户名称： {{shipmentData.ShopName}}</div>
              </div>

              <table v-if="bagCell.ShoShippingBagDetailVos.length === 1">
                <colgroup>
                  <col width="40%">
                  <col width="60%">
                </colgroup>
                <tr>
                  <td>产品号:</td>
                  <td>{{ bagCell.ShoShippingBagDetailVos[0]['OrderProductCode']}}</td>
                  <!--          getFirstCellProductDes['OrderProductCode']           -->
                </tr>
                <tr>
                  <td>产品名称:</td>
                  <td>{{bagCell.ShoShippingBagDetailVos[0]['OrderProductName'] }}</td>
                </tr>
                <tr>
                  <td>包装数量:</td>
                  <td>未知</td>
                </tr>
                <tr>
                  <td>照片数量:</td>
                  <td>

                    <!--    照片产品中的数量的显示视图可以独立出来 (可能有多个)     -->
                    <DetailOfProductOfBag
                      :product-details="bagCell.ShoShippingBagDetailVos[0]['ShippingBagDetailDetailVos']"/>

                  </td>
                </tr>
              </table>

              <!--     合单的情况   显示多个产品  -->
              <template v-if="bagCell.ShoShippingBagDetailVos.length > 1">
                <div @scroll="$_clearCellsPopover(bagCell)" class="multi-wrap">
                  <div :key="product.OrderProductId" class="multi-table-wrap"
                       v-for="(product,idx) in bagCell.ShoShippingBagDetailVos">
                    <table>
                      <colgroup>
                        <col width="50%">
                        <col width="50%">
                      </colgroup>
                      <tr>
                        <td>{{product['OrderProductCode']}}</td>
                        <td>{{product['OrderProductName']}}</td>
                      </tr>
                      <tr>
                        <td colspan="2">
                          <el-popover
                            v-model="product.isEdit"
                            width="160">
                            <p>确认是否删除包裹中的该产品？</p>
                            <div style="text-align: right; margin: 0">
                              <el-button @click="product.isEdit = false" size="mini" type="text">取消</el-button>
                              <el-button @click="confirmRemoveProd(product,bagCell,idx)" size="mini" type="primary">确定
                              </el-button>
                            </div>
                            <i :class="['el-icon-remove',{'rotate':product.isEdit}]"
                               @click="removeBagProd(product)"
                               slot="reference"></i>
                          </el-popover>

                          <DetailOfProductOfBag
                            style="display: inline-block;"
                            :product-details="product.ShippingBagDetailDetailVos"/>
                          <!--<span>5/5 ???</span>-->
                        </td>
                        <!--<td>-->
                          <!--<DetailOfProductOfBag-->
                            <!--:product-details="product.ShippingBagDetailDetailVos"/>-->
                          <!--&lt;!&ndash;   <el-button @click="mergeOrderHandle(bagCell)"/>   &ndash;&gt;-->
                        <!--</td>-->
                      </tr>
                    </table>

                  </div>
                </div>
              </template>

              <!--    v-if="bagCell.ShoShippingBagDetailVos[0]['ShippingBagDetailDetailVos'][0].AllNum <= theMinMergerOrder"             -->

              <!--    合单按钮 => from  (把一个包裹的全部产品合并到另一个包裹)     -->
              <div style="position: absolute;right: -10px;top: -10px;">
                <!--           name="el-fade-in"      -->
                <transition
                  enter-active-class="animated zoomIn"
                  leave-active-class="animated zoomOut"
                >
                  <el-button
                    :disabled="idDoingMergeBag"
                    @click="mergeOrderHandle(bagCell)"
                    circle
                    icon="el-icon-menu"
                    key="merge"
                    size="mini"
                    style="position: absolute;right: 0;top: 0"
                    type="primary"
                    v-if="bagCell['isMerge']===false"/>
                  <el-button
                    @click="cancelMergeOrderHandle(bagCell)"
                    circle
                    icon="el-icon-close"
                    key="cancelMerge"
                    size="mini"
                    style="position: absolute;right: 0;top: 0"
                    type="info"
                    v-if="bagCell['isMerge']===true"/>
                </transition>
              </div>

              <!--    合单按钮 => to     -->
              <div style="position: absolute;left: -10px;top: -10px;">
                <transition
                  enter-active-class="animated zoomIn"
                  leave-active-class="animated zoomOut">
                  <el-button
                    @click="merge2OrderHandle(bagCell)"
                    circle
                    icon="el-icon-bottom-left"
                    size="mini"
                    type="success"
                    v-if="isShowMerge2Btn(bagCell,bagIdx,shipmentData.groupByOrderCode[groupKey])"/>
                </transition>
              </div>

            </div>

          </el-card>
        </el-col>
      </transition-group>

      <el-divider/>
    </div>

  </section>

</template>

<script>

  //  格子信息,仅单面直出
  //  可以操作合单

  import AzureDynamicTable from '@/components/ATheFridayClub/mDynamicTable/AzureDynamicTable'
  import VueBarCode from 'vue-barcode'
  import DetailOfProductOfBag from '@/views/productManagement/aComponents/DetailOfProductOfBag'
  import PackConsignment from '@/views/productManagement/aMixins/PackConsignment'
  import TransactionTable from '@/views/dashboard/admin/components/TransactionTable'
  import {
    AveragePackageBagDetail, ChangePackageBagDetail,
    DeleteBagDetail,
    GetUnCompleteOrder,
    ShippingAviation
  } from '@/api/factoryPresetScan'
  import _ from 'lodash'
  import { ERR_OK } from '@/utils/commons'
  import { getLodop } from '@/views/productManagement/assets/LodopFuncs'
  import hint from '@/mixins/hint'
  import { ecOk } from '@/utils/resHelper'

  export default {
    name: 'DirectOutputPackConsignment',
    components: { TransactionTable, DetailOfProductOfBag, AzureDynamicTable, VueBarCode },
    mixins: [PackConsignment, hint],
    props: {
      //  不在这里判断,外面用动态组件来,这里是只有单面印的
      shipmentData: {
        type: Object,
        default: () => ({})
      }
      // groupByOrderCode: {
      //   type: Object,
      //   default: () => ({})
      // }
    },
    inject: ['shipmentIns'],
    data() {
      return {
        idDoingMergeBag: false, //  当前是否有正在合单的操作
        theMinMergerOrder: 15

      }
    },
    computed: {

      /**
       * @deprecated
       * 获取到第一组格子中的第一个产品的第一个详细
       * @return {Array}
       */
      getFirstCellProductDes() {
        //  每次object keys会不会造成性能问题? 缓存能不能弥补
        const firstGroupList = Object.values(this.groupByOrderCode)[0]
        const firstBagCell = firstGroupList[0]
        return firstBagCell['ShoShippingBagDetailVos'][0]
      }

    },

    created() {
      this.$_clearCellsPopover = _.throttle(this.clearCellsPopover, 100)
    },

    methods: {

      clearCellsPopover(bagCell) {
        console.log('clear popover')
        bagCell.ShoShippingBagDetailVos.forEach((prod) => {
          prod.isEdit = false
        })
      },

      //  用户点击删除
      async confirmRemoveProd(product, bagCell, prodIdx) {
        try {
          const { Result, Code, Message } = await DeleteBagDetail({
            shippingBagCode: bagCell.Code,	//   是	string	　包裹号
            orderProductid: product.OrderProductId,	  //   是	int	　产品名
            fouce: true,	//  是	bool	　强制删除   ture:删除已经打过快递单的产品
            isCleanBagAndRecord: true //	是	bool	　清理空的shippingBag,ShippingRecord
          })
          if (+Code === ERR_OK) {
            return bagCell.ShoShippingBagDetailVos.splice(prodIdx, 1)
          }
          return new Error(Message)
        } catch (e) {
          console.log(e)
        } finally {
          product.isEdit = false
        }

      },
      removeBagProd(product) {
        console.log(product)
      },

      //  get from
      getCurrentMerge() {
        for (const curGroup of Object.values(this.shipmentData.groupByOrderCode)) {
          const find = curGroup.find(e => e.isMerge === true)
          if (_.isObject(find)) {
            return find
          }
        }

      },

      delCurrentMerge() {
        for (const [key, curGroup] of Object.entries(this.shipmentData.groupByOrderCode)) {
          const findIndex = curGroup.findIndex(e => e.isMerge === true)
          if (findIndex) {
            curGroup.splice(findIndex, 1)
            return
          }
        }
      },

      //  用户点击合并订单      (from btn click)
      mergeOrderHandle(bagCell, product, detail) {
        //  false => cancel状态      true => merge2 ready
        // if (Reflect.has(detail, 'isMerge')) {  //  定义响应式对象
        //   this.$set(detail, 'isMerge', false)
        // }
        this.idDoingMergeBag = true //  当前有正在合单的包裹
        bagCell.isMerge = true

        //   // fromShippingNo	是	string	源包裹号
        //   // toShippingNo	是	string	　目标包裹号

      },
      cancelMergeOrderHandle(bagCell) {
        this.idDoingMergeBag = false //  当前有正在合单的包裹
        bagCell.isMerge = false

      },

      //  用户点击合并订单      (to btn click)
      async merge2OrderHandle(toBag) {
        const fromBag = this.getCurrentMerge()

        console.log(fromBag)

        try {
          //  如果不来自同一组,调用合并
          // if (fromBag.OrderBagId !== toBag.OrderBagId) {
            //  调用 合并订单的接口
            // const { default: { Result, Code } } = await import('../mockMergeOrder.js')
            const { Result, Code, ErrorCode, Message } = await ChangePackageBagDetail({
              fromCode: fromBag.Code,
              toCode: toBag.Code
            })

            if (+Code === 1) {
              if (ecOk(ErrorCode)) {
                this.delCurrentMerge()   //  删除掉旧的(merge from)
                this.setMergedData2(Result)  //  合并数据,把新的数据插入到旧的
              }
              this.msg({ ErrorCode, Message })
            }

          // } else {
          //   //  调用 均摊接口
          //   const { Result, Code, ErrorCode, Message } = await AveragePackageBagDetail({
          //     fromCode: fromBag.Code,
          //     toCode: toBag.Code
          //   })
          //   if (+Code === 1) {
          //     ecOk(ErrorCode) && Result.forEach(bagCell => void this.setMergedData2(bagCell))  //  合并数据,把新的数据插入到旧的)
          //     this.msg({ ErrorCode, Message })
          //   }
          // }

          fromBag.isMerge = false //  把from改为false,因为合并包裹完成
          this.shipmentIns.update() //  重新添加 merge属性
          this.idDoingMergeBag = false //  当前有正在合单的包裹

        } catch (e) {
          console.log(e)
        } finally {

        }

      },

      // 把服务器返回的数据替换回去 根据code 包裹编号来进行比较
      setMergedData2(newBagCell) {
        Object.values(this.shipmentData.groupByOrderCode).forEach((group) => {
          const needUpdateIdx = group.findIndex(bagCell => (newBagCell.Code === bagCell.Code))
          group[needUpdateIdx] && group.splice(needUpdateIdx, 1, newBagCell)
        })
      },

      /**
       *  控制 merge target 按钮是否显示
       * @param bagCell
       * @param bagIdx
       * @param cellGroup
       * @return {boolean}
       */
      isShowMerge2Btn(bagCell, bagIdx, cellGroup) {
        //  这种复杂的判断除了责任链模式还能有其他办法?

        //  can not show in self
        if (bagCell.isMerge) {
          return false
        }

        //  current must be has from btn of active state
        if (!this.idDoingMergeBag) {
          return false
        }

        //  去掉了均摊,并且全部都可以来进行合并

        //  (还有一种例外,那就是找倒数第二个来均摊)
        // const currentGroupMerge = cellGroup.some(cell => cell.isMerge)
        // if (currentGroupMerge && cellGroup.length > 1) {
        //   if (cellGroup.length - 2 === bagIdx) {
        //     return true
        //   }
        // }

        //  如果当前是最后一个才显示to按钮
        // if (cellGroup.length - 1 !== bagIdx) {
        //   return false
        // }

        //  根据包裹条件判断,如果当前包裹张数超出max,不显示 todo

        return true
      }

    }
  }
</script>

<style lang="scss" scoped>
  @import "~@/styles/index.scss";

  table {
    border-collapse: collapse;
    width: 200px;

    td {
      border: 1px solid $grayColor;
      text-align: center;
      padding: 3px;
    }
  }

  .bag-wrap {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    min-width: 207px;
    min-height: 220px;
    position: relative;
  }

  .multi-wrap {
    height: 110px;
    overflow-y: auto;
    width: 207px;
    @include scrollBar(4px);

    .multi-table-wrap {

      .rotate {
        transform: rotate(-90deg);
        color: #F56C6C;
      }

      /*&:hover{*/
      /*  .el-icon-remove{*/
      /*    opacity: 1;*/
      /*  }*/
      /*}*/

      .el-icon-remove {
        /*opacity: 0;*/
        transition: all .3s linear;
        cursor: pointer;
        position: relative;
        right: 5px;
        font-size: 15px;
        outline: none;
      }

      table {
        margin-bottom: 15px;
      }
    }


  }


</style>
